
using Abp.Domain.Repositories;
using Abp.EntityFrameworkCore.Repositories;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;


namespace SOEI.Solution.DomainEntities.RoomSourceVerifiyV1.DomainService
{
    /// <summary>
    /// 领域服务层一个模块的核心业务逻辑
    ///</summary>
    public class RoomVerifyV1Manager : DomainServiceBase, IRoomVerifyV1Manager
    {

        private readonly IRepository<RoomVerifyV1, string> _roomverifyv1Repository;

        /// <summary>
        /// 【RoomVerifyV1】的构造方法
        /// 通过构造函数注册服务到依赖注入容器中
        ///</summary>
        public RoomVerifyV1Manager(IRepository<RoomVerifyV1, string> roomverifyv1Repository)
        {
            _roomverifyv1Repository = roomverifyv1Repository;
        }

        #region -------------------------------------------------辅助工具生成---------------------------------------------- 

        /// <summary>
        /// 返回列表查询用
        /// </summary>
        /// <returns></returns>
        public IQueryable<RoomVerifyV1> QueryEntityListAsNoTracking()
        {

            var query = _roomverifyv1Repository.GetAll().AsNoTracking()
                        .Select(x => new RoomVerifyV1
                        {

                            Id = x.Id,
                            FBBT = x.FBBT,
                            FBZTDM = x.FBZTDM,
                            FBZL = x.FBZL,
                            SZC = x.SZC,
                            ZCS = x.ZCS,
                            JZMJ = x.JZMJ,
                            FTMJ = x.FTMJ,
                            TNMJ = x.TNMJ,
                            JZNF = x.JZNF,
                            NSJG = x.NSJG,
                            ZXQK = x.ZXQK,
                            PTSS = x.PTSS,
                            WYSF = x.WYSF,
                            JJRLXDH = x.JJRLXDH,
                            JJRBH = x.JJRBH,
                            BZ = x.BZ,
                            FBSJ = x.FBSJ,
                            WTSJ = x.WTSJ,
                            WTJZRQ = x.WTJZRQ,
                            LPMC = x.LPMC,
                            SQ = x.SQ,
                            ZBPT = x.ZBPT,
                            JTQK = x.JTQK,
                            KFSJ = x.KFSJ,
                            WTHTBH = x.WTHTBH,
                            CKYG = x.CKYG,
                            XQ = x.XQ,
                            HX = x.HX,
                            YT = x.YT,
                            JZJG = x.JZJG,
                            CX = x.CX,
                            JJRXM = x.JJRXM,
                            JGBH = x.JGBH,
                            XGSJ = x.XGSJ,
                            FWDJ = x.FWDJ,
                            SQSJ = x.SQSJ,
                            GPLXDM = x.GPLXDM,
                            GPBLZTDM = x.GPBLZTDM,
                            FYHYMBH = x.FYHYMBH,
                            FYMS = x.FYMS,
                            BH = x.BH,
                            FYHYM = x.FYHYM,
                            QDM = x.QDM,
                            JNZB_X = x.JNZB_X,
                            JNZB_Y = x.JNZB_Y,
                            BDZB_X = x.BDZB_X,
                            BDZB_Y = x.BDZB_Y,
                            FWZT = x.FWZT,
                            FWBH = x.FWBH,
                            LRSJ = x.LRSJ,
                            WZGUID = x.WZGUID,
                            DJSQBH = x.DJSQBH,
                            FYYXQ = x.FYYXQ,
                            SFGSLXRDH = x.SFGSLXRDH,
                            SFBDC = x.SFBDC,
                            CQZBH = x.CQZBH,
                            CQZH = x.CQZH,
                            WZSQRXM = x.WZSQRXM,
                            WZSQRZJHM = x.WZSQRZJHM,
                            WZSQRZJLXDM = x.WZSQRZJLXDM,
                            SJLY = x.SJLY,
                        });
            return query;
        }

        /// <summary>
        /// 【RoomVerifyV1】返回表达式数的实体信息即IQueryable类型
        /// </summary>
        /// <returns>IQueryable</returns>
        public IQueryable<RoomVerifyV1> Query()
        {
            return _roomverifyv1Repository.GetAll();
        }
        /// <summary>
        /// 【RoomVerifyV1】返回即IQueryable类型的实体，不包含EF Core跟踪标记
        /// </summary>
        /// <returns>IQueryable</returns>
        public IQueryable<RoomVerifyV1> QueryAsNoTracking()
        {
            return _roomverifyv1Repository.GetAll().AsNoTracking();
        }
        /// <summary>
        /// 【RoomVerifyV1】根据Id查询实体信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns>实体</returns>
        public async Task<RoomVerifyV1> FindByIdAsync(string id)
        {
            var entity = await _roomverifyv1Repository.GetAsync(id);
            return entity;
        }
        /// <summary>
        /// 【RoomVerifyV1】检查实体是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns>bool</returns>
        public async Task<bool> IsExistAsync(string id)
        {
            var result = await _roomverifyv1Repository.GetAll().AnyAsync(a => a.Id == id);
            return result;
        }
        /// <summary>
        /// 【RoomVerifyV1】创建实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<RoomVerifyV1> CreateAsync(RoomVerifyV1 entity)
        {
            entity.Id = await _roomverifyv1Repository.InsertAndGetIdAsync(entity);
            return entity;
        }
        /// <summary>
        /// 【RoomVerifyV1】更新实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task UpdateAsync(RoomVerifyV1 entity)
        {
            await _roomverifyv1Repository.UpdateAsync(entity);
        }
        /// <summary>
        /// 【RoomVerifyV1】删除实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteAsync(string id)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _roomverifyv1Repository.DeleteAsync(id);
        }
        /// <summary>
        /// 【RoomVerifyV1】批量删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task BatchDelete(List<string> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _roomverifyv1Repository.DeleteAsync(a => input.Contains(a.Id));
        }
        #endregion


        #region -------------------------------------------------用户自定义------------------------------------------------
        /*请在此扩展领域服务接口*/

        /// <summary>
        /// 
        /// </summary>
        /// <param name="SFBDC">产权证号码下拉</param>
        /// <param name="CQZH">产权证号</param>
        /// <param name="WZSQRZJLXDM">证件类型下拉</param>
        /// <param name="WZSQRZJHM">证件号码</param>
        /// <param name="WZSQRXM">产权人姓名</param>
        /// <returns></returns>
        public async Task<string> ForCheck(string SFBDC, string CQZH, string WZSQRZJLXDM, string WZSQRZJHM, string WZSQRXM)
        {
            #region sample
            //var vParam = ParamCollect.FromObj(new
            //{
            //    IS_CQZH = CQZH,
            //    IS_CQRMC = WZSQRXM,
            //    IS_ZJHM = WZSQRZJHM
            //}, ParameterDirection.Input);

            //vParam.AddFromObj(new
            //{
            //    //OC_CURSOR = "",
            //    OS_RETURN = 0,
            //    OS_ERRORINF = ""
            //}, ParameterDirection.Output);

            //var ds = await _roomverifyv1Repository.GetDbContext().Database.ExecuteStoreProcedure("PKG_CLFWQ_JJHT_BDC.SP_GETCQRXX", vParam, "CURSOR");

            ////return vParam.GetDynamic().oc_cursor;
            //var vList = ds.Tables[0].ToList<dynamic>();

            //var dict = vList[0] as IDictionary<string, object>;

            //foreach (var item in dict)
            //{
            //    if (item.Key == "CQZBH")
            //    {
            //        return item.Value as string;
            //    }
            //} 
            #endregion

            int co = 0;

            string vCQZXX = string.Empty;
            string vCQZH = CQZH;
            string vCQR = WZSQRXM;
            string vZJLX = string.Empty;
            string vZJHM = WZSQRZJHM;
            string vCQZBH = string.Empty;
            //判断产权证限制
            string vCQZHCQZX = string.Empty;

            vZJLX = ",10";

            vZJLX = vZJLX.Substring(1, vZJLX.Length - 1);

            string vCOUNT = "1";

            co = Convert.ToInt32(vCOUNT.ToString());


            #region 产权证号记录日志

            var vParamInsertCQZHLog = ParamCollect.FromObj(new
            {
                IS_CQZH = CQZH,
                //IS_LRRY = user.UserName
                IS_LRRY = base.CurrentUser.UserName
            }, ParameterDirection.Input);

            vParamInsertCQZHLog.AddFromObj(new
            {
                OS_CQZHRZBH = "",
                OS_RETURN = 0,
                OS_ERRORINF = ""
            }, ParameterDirection.Output);

            await _roomverifyv1Repository.GetDbContext().Database.ExecuteStoreProcedure("PKG_CLFWQ_WTHT.c_SP_InsertCQZHLog", vParamInsertCQZHLog);

            string vCQZHBH = vParamInsertCQZHLog.GetDynamic().OS_CQZHRZBH;

            #endregion

            #region 产权人记录日志

            for (int i = 0; i < co; i++)
            {
                var vParamInsertCQRXXLog = ParamCollect.FromObj(new
                {
                    IS_CQZHRZBH = vCQZHBH,
                    IS_CQRXM = WZSQRXM,
                    IS_ZJHM = WZSQRZJHM,
                    //IS_LRRY = user.UserName
                    IS_LRRY = base.CurrentUser.UserName
                });

                //vParamInsertCQRXXLog.Add(new ParamItem() { Name = "OS_MSG", Direction = ParameterDirection.Output });

                //vParamInsertCQRXXLog.AddFromObj(new
                //{
                //    OS_RETURN = 0,
                //    OS_ERRORINF = ""
                //}, ParameterDirection.Output);

                await _roomverifyv1Repository.GetDbContext().Database.ExecuteStoreProcedure("PKG_CLFWQ_WTHT.c_SP_InsertCQRXXLog", vParamInsertCQRXXLog);
            }

            #endregion

            #region 获取委托合同产权人信息

            var vParamGETCQRXX = ParamCollect.FromObj(new
            {
                IS_CQZH = CQZH,
                IS_CQRMC = WZSQRXM,
                IS_ZJHM = WZSQRZJHM
            }, ParameterDirection.Input);

            vParamGETCQRXX.AddFromObj(new
            {
                OS_RETURN = 0,
                OS_ERRORINF = ""
            }, ParameterDirection.Output);

            DataSet dsCQRXX = await _roomverifyv1Repository.GetDbContext().Database.ExecuteStoreProcedure("PKG_CLFWQ_JJHT_BDC.SP_GETCQRXX", vParamGETCQRXX, "cursor");
            #endregion

            if (null == dsCQRXX || dsCQRXX.Tables.Count < 1 || dsCQRXX.Tables[0].Rows.Count < 1)
            {
                return "{\"cqzbh\":\"\",\"msg\":\"此房屋所有权证信息无效，请查证后输入！\"}";
            }

            if (dsCQRXX.Tables[0].Rows.Count > 1)
            {
                string vTempCQZBH = "";
                bool vResult = true;
                for (int i = 0; i < dsCQRXX.Tables[0].Rows.Count; i++)
                {
                    if (vTempCQZBH == "" || vTempCQZBH == dsCQRXX.Tables[0].Rows[i]["CQZBH"].ToString())
                    {
                        vTempCQZBH = dsCQRXX.Tables[0].Rows[i]["CQZBH"].ToString();
                    }
                    else
                    {
                        vResult = false;
                    }
                }

                if (!vResult)
                {
                    return "{\"cqzbh\":\"\",\"msg\":\"存在重复的产权证信息，请核档！\"}";
                }

            }

            if (dsCQRXX.Tables[0].Rows.Count == 1)
            {
                vCQZBH = dsCQRXX.Tables[0].Rows[0]["CQZBH"].ToString();
            }
            else
            {
                for (int i = 0; i < dsCQRXX.Tables[0].Rows.Count; i++)
                {
                    if (vCQZH == dsCQRXX.Tables[0].Rows[i]["BDCQZBM"].ToString())
                    {
                        vCQZBH = dsCQRXX.Tables[0].Rows[i]["CQZBH"].ToString();
                    }
                }
            }

            string[] vListCQR = vCQR.Split(',');
            string[] vListZJLX = vZJLX.Split(',');
            string[] vListZJHM = vZJHM.Split(',');

            if (vListCQR.Length != dsCQRXX.Tables[0].Rows.Count)
            {
                return "{\"cqzbh\":\"\",\"msg\":\"产权人信息与不动产证信息不匹配！\"}";
            }

            string vCQXXArray = string.Empty;
            for (int i = 0; i < dsCQRXX.Tables[0].Rows.Count; i++)
            {
                if (dsCQRXX.Tables[0].Rows[i]["ZJLXDM"].ToString() == "10" && dsCQRXX.Tables[0].Rows[i]["ZJHM"].ToString().Length == 15)
                {
                    vCQXXArray += dsCQRXX.Tables[0].Rows[i]["CQRMC"].ToString() + "|" + BusinessUtils.GetCardID(dsCQRXX.Tables[0].Rows[i]["ZJHM"].ToString()) + "|";
                }
                else
                {
                    vCQXXArray += dsCQRXX.Tables[0].Rows[i]["CQRMC"].ToString() + "|" + dsCQRXX.Tables[0].Rows[i]["ZJHM"].ToString().ToUpper() + "|";
                }
            }
            for (int j = 0; j < co; j++)
            {
                if (vListZJLX[j].ToString() == "10" && vListZJHM[j].ToString().Length == 15)
                {
                    vCQXXArray = vCQXXArray.Replace(vListCQR[j].ToString() + "|" + BusinessUtils.GetCardID(vListZJHM[j].ToString()) + "|", "");
                }
                else
                {
                    vCQXXArray = vCQXXArray.Replace(vListCQR[j].ToString() + "|" + vListZJHM[j].ToString().ToUpper() + "|", "");
                }
            }
            if (vCQXXArray != "")
            {
                return "{\"cqzbh\":\"\",\"msg\":\"产权人信息与不动产证信息不匹配！\"}";
            }

            #region 校验产权证信息

            var vParamCHECK_CQZXX = ParamCollect.FromObj(new
            {
                IS_CQZBH = vCQZBH,
                //IS_JGBH = user.OriginalNumber,
                //IS_JGBH = "000041",
                IS_JGBH = base.CurrentUser.OriginalNumber,
                IS_WTHTBH = "00000"
            }, ParameterDirection.Input);

            vParamCHECK_CQZXX.AddFromObj(new
            {
                OS_RETURN = 0,
                OS_ERRORINF = ""
            }, ParameterDirection.Output);

            await _roomverifyv1Repository.GetDbContext().Database.ExecuteStoreProcedure("PKG_CLFWQ_JJHT_BDC.SP_CHECK_CQZXX", vParamCHECK_CQZXX);

            var vMsg = vParamCHECK_CQZXX.GetDynamic().OS_ERRORINF.ToString();

            #endregion

            #region 处理返回的Mess为自己所需的Mess
            if (!string.IsNullOrWhiteSpace(vMsg))
            {
                if (vMsg.IndexOf("此产权证已经签订独家委托合同！") > -1 || vMsg.IndexOf("此产权信息已签交易合同，不能再签订居间合同！") > -1 || vMsg.IndexOf("此产权证在本机构名下已签居间合同，不能再签订") > -1)
                {
                    vMsg = "";
                }
                if (vMsg.IndexOf("，不能签订居间合同") > -1 || vMsg.IndexOf("，请核实后再执行本次操作") > -1)
                {
                    vMsg = vMsg.Split('，')[0] + "，不能上市交易！";
                }
            }
            #endregion

            if (!string.IsNullOrWhiteSpace(vMsg))
            {
                return "{\"cqzbh\":\"\",\"msg\":\"" + vMsg + "\"}";
            }

            #region 产权限制

            var vParamCHECK_CQZXZ = ParamCollect.FromObj(new
            {
                is_CQZBH = CQZH
            }, ParameterDirection.Input);

            vParamCHECK_CQZXZ.AddFromObj(new
            {
                OS_RETURN = 0,
                OS_ERRORINF = ""
            }, ParameterDirection.Output);

            await _roomverifyv1Repository.GetDbContext().Database.ExecuteStoreProcedure("PKG_CLFWQ_CLFMMHT_BDC.SP_CHECK_CQZXZ", vParamCHECK_CQZXZ);

            //vMsg = vParamCHECK_CQZXZ.GetDynamic().OS_ERRORINF;
            vMsg = vParamCHECK_CQZXZ.GetDynamic().OS_ERRORINF;

            "aa".ToString();

            vMsg = vMsg.ToString();


            #endregion

            if (!string.IsNullOrWhiteSpace(vMsg))
            {
                return "{\"cqzbh\":\"\",\"msg\":\"此产权证信息存在限制，不能上市交易！\"}";
            }
            //查找产权证对应的房屋用途是否是“人防”，房屋用途为“人防”的房子不能签订合同。

            #region 产权证对应的房屋用途

            var vParamCHECK_FWYT = ParamCollect.FromObj(new
            {
                is_CQZBH = CQZH
            }, ParameterDirection.Input);

            //vParamCHECK_FWYT.AddFromObj(new
            //{
            //    OS_RETURN = 0,
            //    OS_ERRORINF = ""
            //}, ParameterDirection.Output);

            await _roomverifyv1Repository.GetDbContext().Database.ExecuteStoreProcedure("PKG_CLFWQ_WTHT_BDC.c_SP_CHECK_FWYT", vParamCHECK_FWYT);

            //vMsg = vParamCHECK_FWYT.GetDynamic().OS_ERRORINF.ToString();

            vMsg = vParamCHECK_FWYT["OS_ERRORINF"].Value as string;
            #endregion

            if (!string.IsNullOrWhiteSpace(vMsg))
            {
                return "{\"cqzbh\":\"\",\"msg\":\"此产权证对应的房屋用途为人防，不能上市交易！\"}";
            }

            string result = "{\"cqzbh\":\"" + vCQZBH + "\",\"msg\":\"\"}";

            return result;

        }


        #endregion









    }
}
